const express = require('express');
const router = express.Router();
const R = require("../util/json")
const connection = require("../util/db")
const json = require("../util/jsonFormat")
const md5 = require("md5")
const {formatArray,formatObject} = require("../util/jsonFormat");

function extracted(sql,objs,query) {
    const {username,nickname,phone,status,roleId,departmentId} = query;
    if (username) {
        sql += 'and username = ? ';
        objs.push(username);
    }
    if (nickname) {
        sql += 'and nickname like ? ';
        objs.push(`%${nickname}%`);
    }
    if (phone) {
        sql += 'and phone = ? ';
        objs.push(phone);
    }
    if (status) {
        sql += 'and u.status = ? ';
        objs.push(status);
    }
    if (roleId) {
        sql += "and role_id = ? ";
        objs.push(roleId)
    }
    if (departmentId) {
        sql += "and department_id = ? ";
        objs.push(departmentId);
    }
    return sql;
}

router.get("/page",function (req, res) {
    const {page=1,limit=5} = req.query;
    const offset = (page-1)*limit;
    let sql = "select u.*,r.role_name,d.department_name from userinfo u left join role r on u.role_id = r.id left join department d on u.department_id = d.id where 1 = 1 ";
    const objs = [];
    sql = extracted(sql,objs,req.query);
    sql+='order by u.id desc limit ?,?';
    objs.push(offset,parseInt(limit));
    connection.query(sql,objs,function (e,r) {
        if(e){
            throw e;
        }
        const userList = formatArray(r);
        let countSql = "select count(u.id) count from userinfo u left join role r on u.role_id = r.id left join department d on u.department_id = d.id where 1 = 1 ";
        const countObjs = [];
        countSql=extracted(countSql,countObjs,req.query);
        connection.query(countSql,countObjs,function (e,r) {
            if(e){
                throw e;
            }
            const count = r[0].count;
            res.json(R.page(count,userList));
        })
    })
})

router.get(["/info/:id","/info"],function (req, res) {
    const id = req.params.id || req.loginId;
    connection.query("select u.*,r.role_name,d.department_name from userinfo u left join role r on u.role_id = r.id left join department d on u.department_id = d.id where u.id = ?",[id],function (e,r) {
        if(e){
            throw e;
        }
        if(r.length > 0){
            res.json(R.data(formatObject(r[0])))
        }else{
            res.json(R.error("编号异常"))
        }
    })
})

router.post("/update",function (req, res) {
    const userinfo = req.body;
    if(userinfo.id){
        let sql = "update userinfo set nickname = ?,phone = ?,status = ?,avatar = ?,role_id = ?,department_id = ?,is_driver = ?,driver_photo1 = ?,driver_photo2 = ? where id = ?";
        const objs=[userinfo.nickname,userinfo.phone,userinfo.status,userinfo.avatar,userinfo.roleId,userinfo.departmentId?userinfo.departmentId:null,userinfo.isDriver,userinfo.driverPhoto1,userinfo.driverPhoto2,userinfo.id];
        connection.query(sql,objs,function (e) {
            if(e){
                throw e;
            }
            res.json(R.ok());
        })
    }else{
        connection.query("select * from userinfo where username = ?",[userinfo.username],function (e,r) {
            if(e){
                throw e;
            }
            if(r.length > 0){
                res.json(R.error("用户名已存在"));
            }else{
                let sql = "insert into userinfo values(null,?,?,?,?,?,?,?,?,?,?,?)";
                const objs=[userinfo.username,md5("123456"),userinfo.nickname,userinfo.status,userinfo.avatar,userinfo.phone,userinfo.roleId,userinfo.departmentId?userinfo.departmentId:null,userinfo.isDriver,userinfo.driverPhoto1,userinfo.driverPhoto2];
                connection.query(sql,objs,function (e) {
                    if(e){
                        throw e;
                    }
                    res.json(R.ok());
                })
            }
        })
    }
})

router.delete("/delete/:id",function (req, res) {
    const {id} = req.params;
    if(id == 1){
        res.json(R.error("超级管理员禁止删除"));
    }else if(id == req.loginId){
        res.json(R.error("当前登录用户禁止删除"));
    }else{
        connection.query("delete from userinfo where id = ?",[id],function (e) {
            if(e){
                throw e;
            }
            res.json(R.ok());
        })
    }
})

router.post("/status",function (req,res) {
    const {id,status} = req.body;
    if(id === 1){
        res.json(R.error("超级管理员不能更改状态"));
    }else if(id === req.loginId) {
        res.json(R.error("当前登录用户不能更改状态"));
    }else{
        let sql = "update userinfo set status = ? where id = ?";
        const objs = [status,id];
        connection.query(sql,objs,function (e) {
            if(e){
                throw e;
            }
            res.json(R.ok());
        })
    }
})

router.post("/password",function (req, res){
    const {oldPassword,password} = req.body;
    const id = req.loginId;

    let sql = "select * from userinfo where id = ? and password = ?";
    const objs=[id,md5(oldPassword)];
    connection.query(sql,objs,function (e,r) {
        if(e){
            throw e;
        }
        if(r.length > 0){
            sql = "update userinfo set password = ? where id = ?";
            connection.query(sql,[md5(password),id],function (e) {
                if(e){
                    throw e;
                }
                res.json(R.ok());
            })
        }else{
            res.json(R.error("原密码不正确！"));
        }
    })
})

router.get("/driver/select",function (req, res) {
    connection.query("select * from userinfo where role_id = 4",function (e,r) {
        if(e){
            throw e;
        }
        res.json(R.data(json.formatArray(r)));
    })
})


module.exports = router;
